import { WebSocketGateway, SubscribeMessage, MessageBody, ConnectedSocket, WebSocketServer } from '@nestjs/websockets';
import { BookService } from './book.service';
import { CreateBookDto } from './dto/create-book.dto';
import { UpdateBookDto } from './dto/update-book.dto';
import { Observable } from 'rxjs';
import { Server } from 'socket.io';

// @WebSocketGateWay 声明这是一个处理 weboscket 的类。
@WebSocketGateway()
export class BookGateway {
    constructor(private readonly bookService: BookService) { }

    /* 
    也可以选择注入示例来实现websocket  `npm install socket.io`
    - @WebSocketServer
    - @ConnectedSocket
    */
    
    // @WebSocketServer 注入实例
    @WebSocketServer()
    server: Server;

    // @SubscribeMessage 是指定处理的消息。
    // @MessageBody 取出传过来的消息内容
    @SubscribeMessage('createBook')
    create(@MessageBody() createBookDto: CreateBookDto) {
        return this.bookService.create(createBookDto);
    }

    @SubscribeMessage('findAllBook')
    findAll() {
        return {
            event: 'lrq',  // 指定event 和 data
            data: this.bookService.findAll()
        };
    }

    @SubscribeMessage('findOneBook')
    findOne(@MessageBody() id: number) {
        return new Observable((observer) => {
            observer.next({ event: 'lrq', data: { msg: 'aaa' } });
            // 服务端会在根据定时器 依次发送数据
            setTimeout(() => {
                observer.next({ event: 'lrq', data: { msg: 'bbb' } });
            }, 2000);

            setTimeout(() => {
                observer.next({ event: 'lrq', data: { msg: 'ccc' } });
            }, 5000);
        });
    }

    @SubscribeMessage('updateBook' ) // @ConnectedSocket 装饰器注入实例
    update(@MessageBody() updateBookDto: UpdateBookDto , @ConnectedSocket() server : Server) {
        server.emit('test-server' , '测试')
        return this.bookService.update(updateBookDto.id, updateBookDto);
    }

    @SubscribeMessage('removeBook')
    remove(@MessageBody() id: number) {
        return this.bookService.remove(id);
    }
}
